#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import time, hashlib, base64, json, requests, datetime
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from random import Random
from Crypto.Cipher import AES
import urllib.parse
from decimal import Decimal
from django.db import transaction

from users.models import Level, User, CustomerUser
from merchants.models import Merchant, MerchantEnter, MerchantChannel, MerchantImage, MerchantUser
from activities.models import Activity, ActivityLevel, ActivityLevelRecord, PointRecord,Channel
from goods.models import *
from orders.models import *
from equity_mall.utils.qiniu_storage import pic_upload
from vouchers.models import *
from equity_mall.utils.sync_img_to_local import sync_img_to_local, make_qrcode
from random import randint
from cashbonus.models import *


def get_sign(data_dict, secret):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&secret=' + secret
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def decrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = cryptor.decrypt(text)
    return bytes.decode(plain_text).rstrip('\0').rstrip("\x01").rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def get_result(method, body):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NTI4NzU4NjUsImlhdCI6MTY1MjgzMjY2NSwidXNlcklkIjoiMjM4NDAzMTYyODQxNzU0ODQ1In0.Ry0JHx-HiZJj7UfvW50MXPnAcnoKniiLKVXaTdIKAi4'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp
    }
    url = f'https://i.wxmas.com/company-gateway/api?data={urllib.parse.quote(data)}&method={method}'
    response = requests.get(url=url, headers=headers)
    return decrypt(response.json()['data'], key, iv)


def post_result(method, body):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NTE4NDA3NTcsImlhdCI6MTY1MTc5NzU1NywidXNlcklkIjoiMjM4NDAzMTYyODQxNzU0ODQ1In0.OEOlNBV-FH7NkOJZ8SyYugcYTTpeXRz2F9zQdZIkoA4'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://i.wxmas.com/company-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def pull_ri_companyuser():
    print('%s: pull_ri_companyuser' % time.ctime())
    method = 'companyUserList'
    page = 1
    is_break = 0
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['manageList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['wyh_id'] = i['id']
            user_data['username'] = i['name']
            user_data['nickname'] = i['name']
            user_data['mobile'] = i['phone']
            user_data['platform'] = 2
            user_data['role_id'] = 3
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            if i['isUse']:
                user_data['is_active'] = 1
            else:
                user_data['is_active'] = 0
            try:
                level = Level.objects.filter(orgId=i['orgIds'][0]).first()
                user_data['OrgId'] = i['orgIds'][0]
                if level:
                    user_data['level_id'] = level.id
            except:
                pass
            user_data['account'] = i['jobNumber']
            try:
                instance, create = User.objects.get_or_create(mobile=user_data['mobile'], defaults=user_data)
                if create:
                    print(instance.id)
            except:
                print(i['phone'])
        page += 1


def pull_ri_merchant():
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    is_break = 0
    page = 1
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        print(body)
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            user_data = {}
            enter_data = {}
            enter_data['id'] = i['id']
            user_data['name'] = i['name']
            user_data['managerName'] = i['managerName']
            user_data['managermobile'] = i['managerMobile']
            user_data['wyfMerchantID'] = i['wyfMerchantID']
            user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
            enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')

            try:
                instance, create = Merchant.objects.get_or_create(wyfMerchantID=user_data['wyfMerchantID'], defaults=user_data)
                if create:
                    print(instance.id)
                enter_data['merchant_id'] = instance.id
                try:
                    level = Level.objects.filter(orgId=i['orgID']).first()
                    enter_data['OrgId'] = i['orgID']
                    if level:
                        enter_data['level_id'] = level.id
                except:
                    pass
                enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
            except Exception as e:
                print(i['managerMobile'])
        page += 1


def pull_ri_activity():
    print('%s: pull_ri_activity' % time.ctime())
    method = 'GiftBagPointGetActivityList'
    # body = {"page": '1', 'pageSize': '1'}
    # print(get_result(method, body))
    is_break = 0
    page = 1
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '100'}
        result = json.loads(get_result(method, body))['data']['activityList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['activity_id'] = i['id']
            user_data['name'] = i['name']
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['platform'] = 2
            user_data['available_begin_time'] = i['timeRule']['startedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['available_end_time'] = i['timeRule']['endedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['max_point'] = i['totalPoint']
            user_data['distributed_point'] = i['receivePoint']
            try:
                level = Level.objects.filter(orgId=i['orgId']).first()
                user_data['OrgId'] = i['orgId']
                if level:
                    level.point += int(i['totalPoint'])
                    level.save()
                    user_data['level_id'] = level.id
            except:
                pass
            try:
                user = User.objects.filter(orgId=i['wyh_id']['userId']).first()
                if user:
                    user_data['create_user_id'] = user.id
                else:
                    user_id=None
            except:
                user_id=None
            try:
                instance, create = Activity.objects.update_or_create(activity_id=user_data['activity_id'], defaults=user_data)
                if create:
                    print(instance.id)
                    activity_level = ActivityLevel.objects.create(
                        level_id=instance.level_id,
                        activity_id=instance.id,
                        max_point=instance.max_point
                    )
                    ActivityLevelRecord.objects.create(
                        activity_level_id=activity_level.id,
                        point=activity_level.max_point,
                        operation_type=1,
                        user_id=user_id,
                        create_time=i['createdAt'].replace('T', ' ').replace('+08:00', ''),
                        level_id=instance.level_id,
                    )
                # else:
                #     is_break = 1
                #     break
            except:
                print(i['name'])
        page += 1


def pull_point_record():
    print('%s: pull_point_record' % time.ctime())
    method = 'GiftBagPointGetAllotRecordList'
    body = {"page":"1","pageSize":"10","source":"allot","actId":"282101895965851648","orgId":"176044788054528000"}
    print(get_result(method, body))
    # query_set = ActivityLevel.objects.all()
    # for instance in query_set:
    #     level = instance.level
    #     body = {"page": "1", "pageSize": "10", "source": "allot", "actId": "282101895965851648", "orgId": level.orgId}
    #     result = json.loads(get_result(method, body))['data']['recordList']


def pull_ri_user():
    print('%s: pull_ri_user' % time.ctime())
    method = 'MemberList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(get_result(method, body))
    is_break = 0
    page = 1
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '10', 'openId': 'oI_D75XzTUiAIuV9dEb9fJ5HEKGQ'}
        print(body)
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            user_data = {}
            # user_data['user_id'] = i['Id']
            user_data['mobile'] = i['Mobile']
            user_data['old_openid'] = i['Openid']
            user_data['is_distributor'] = i['isDistributor']
            user_data['idcode'] = i['idcode']
            user_data['realname'] = i['realname']
            user_data['username'] = i['nickname']
            user_data['address'] = i['address']
            user_data['is_offline'] = i['offlineMember']
            user_data['point'] = i['localpoint']
            user_data['avatar'] = i['avatar']
            user_data['create_time'] = i['CreatedAt'].replace('T', ' ').replace('+08:00', '')
            try:
                instance, create = CustomerUser.objects.update_or_create(mobile=user_data['mobile'], defaults=user_data)
                if create:
                    print(instance.id)
                # else:
                #     is_break = 1
                #     break
            except Exception as e:
                print(i['Mobile'], e)
        page += 1


def pull_merchant(wyfMerchantID):
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    body = {"page": '1', 'pageSize': '1', "ruiyinxinMerchantID": wyfMerchantID}
    result = json.loads(get_result(method, body))['data']['list']
    i = result[0]
    user_data = {}
    enter_data = {}
    enter_data['id'] = i['id']
    user_data['name'] = i['name']
    user_data['managerName'] = i['managerName']
    user_data['managermobile'] = i['managerMobile']
    user_data['wyfMerchantID'] = i['wyfMerchantID']
    user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
    enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = Merchant.objects.get_or_create(wyfMerchantID=user_data['wyfMerchantID'], defaults=user_data)
    if create:
        print(instance.id)
    enter_data['merchant_id'] = instance.id
    try:
        level = Level.objects.filter(orgId=i['orgID']).first()
        enter_data['OrgId'] = i['orgID']
        if level:
            enter_data['level_id'] = level.id
    except:
        pass
    enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
    return instance


def pull_goods(id):
    print('%s: pull_ri_goods' % time.ctime())
    method = 'GoodsList'
    body = {"page": '1', 'pageSize': '1', 'id': id}
    result = json.loads(get_result(method, body))['data']['list']
    i = result[0]
    user_data = {}
    user_data['id'] = i['id']
    user_data['name'] = i['name']
    user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    user_data['equityID'] = i['equityID']
    user_data['point'] = i['exchangeNumber']
    default_image = f'youhuiquanyi/{i["supplierDetail"]["wyfMerchantID"]}/default_image{i["equityID"]}.png'
    pic_upload(requests.get(i['images'][0]['url']).content, key=default_image)
    user_data['default_image'] = default_image
    user_data['desc_detail'] = i['detail']
    user_data['category_id'] = 1
    try:
        merchant = Merchant.objects.filter(wyfMerchantID=i["supplierDetail"]["wyfMerchantID"]).first()
        if merchant:
            user_data['merchant_id'] = merchant.id
        else:
            merchant = pull_merchant(wyfMerchantID=i["supplierDetail"]["wyfMerchantID"])
            user_data['merchant_id'] = merchant.id
    except:
        pass
    if not i['isSale']:
        is_launched = 0
    else:
        is_launched = 1
    try:
        instance, create = Goods.objects.update_or_create(id=user_data['id'], defaults=user_data)
        print(instance.id)
        level = Level.objects.filter(orgId=i['orgId']).first()
        launchedgoods = LaunchedGoods.objects.create(
            name=instance.name,
            caption=instance.caption,
            goods=instance,
            category_id=1,
            point=instance.point,
            is_launched=is_launched,
            level=level,
            create_time=instance.create_time
        )
        GoodsImage.objects.create(
            goods=instance,
            image=instance.default_image
        )
        return launchedgoods
    except Exception as e:
        print(e)
        print(i['name'])


def pull_user(userMobile):
    print('%s: pull_ri_user' % time.ctime())
    method = 'MemberList'
    body = {"page": '1', 'pageSize': '1', 'Mobile': userMobile}
    # print(get_result(method, body))
    result = json.loads(get_result(method, body))['data']['list'][0]
    user_data = {}
    # user_data['user_id'] = i['Id']
    user_data['mobile'] = result['Mobile']
    user_data['old_openid'] = result['Openid']
    user_data['is_distributor'] = result['isDistributor']
    user_data['idcode'] = result['idcode']
    user_data['realname'] = result['realname']
    user_data['username'] = result['nickname']
    user_data['address'] = result['address']
    user_data['is_offline'] = result['offlineMember']
    user_data['point'] = result['localpoint']
    user_data['avatar'] = result['avatar']
    user_data['create_time'] = result['CreatedAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = CustomerUser.objects.update_or_create(mobile=user_data['mobile'], defaults=user_data)
    return instance


def pull_orderinfo():
    print('%s: pull_ri_order_info' % time.ctime())
    method = 'OrderList'
    # body = {"page": '1', 'pageSize': '1'}
    # print(get_result(method, body))
    startTime = datetime.datetime.now() + datetime.timedelta(days=-2)
    startTime = startTime.strftime("%Y-%m-%dT00:00:00+08:00")
    now_date = datetime.datetime.now()
    endTime = now_date.strftime("%Y-%m-%dT23:59:59+08:00")
    STATE_ENUM = {
        'WAIT': 1,
        'PAID': 2,
        'SUCCESS': 3,
        'EXPIRED': 4,
        'AFTERSALE': 5,
        'SHIP': 6,
        'RESERVE': 7,
        'REFUNDED': 8,
        'SENDING': 9,
        'REFUNDING': 10,
        'ABNORMA': 11
    }
    page = 1
    is_break = 0
    # startTime = '2021-07-27T00:00:00+08:00'
    # endTime='2021-07-27T23:59:59+08:00'
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '1000', "time": [startTime, endTime]}
        print(body)
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result[::-1]:
            if i['usePoint'] != '0':
                user_data = {}
                user_data['order_id'] = i['id']
                user_data['orderNum'] = i['orderNum']
                user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
                user_data['state'] = STATE_ENUM[i['state']]
                user_data['platform'] = 2
                try:
                    launchedgoods = LaunchedGoods.objects.get(goods__equityID=i['equityId'])
                    if not launchedgoods:
                        launchedgoods = pull_goods(i['goodsId'])
                    rimerchant = launchedgoods.goods.merchant
                    if rimerchant:
                        user_data['merchant_id'] = rimerchant.id
                        user_data['level'] = rimerchant.level
                except:
                    pass
                try:
                    riuser = CustomerUser.objects.filter(mobile=i['userMobile']).first()
                    if riuser:
                        user_data['customer_user_id'] = riuser.id
                    else:
                        riuser = pull_user(i['userMobile'])
                        riuser = CustomerUser.objects.get(id=riuser.id)
                        user_data['customer_user_id'] = riuser.id
                except:
                    pass
                user_data['point'] = Decimal(i['usePoint'])
                try:
                    instance, create = OrderInfo.objects.update_or_create(orderNum=user_data['orderNum'], defaults=user_data)
                    if create:
                        print(instance.id)
                        OrderGoods.objects.create(
                            order=instance,
                            launched_goods=launchedgoods,
                            count=i['num'],
                            price=launchedgoods.price,
                            point=launchedgoods.point
                        )
                        instance = OrderInfo.objects.get(id=instance.id)
                        riuser.point -= instance.point
                        riuser.save()
                        PointRecord.objects.create(
                            customer_user_id=riuser.id,
                            create_time=instance.create_time,
                            operate_type=2,
                            business_type=2,
                            point=instance.point,
                            point_balance=riuser.point,
                            order_id=instance.id
                        )
                    # else:
                    #     is_break = 1
                    #     break
                except Exception as e:
                    print(e)
                    print(i['name'])
        page += 1


def wash_coupon():
    queryset = AliDiscountCouponLevel.objects.filter(activity_id=55, level__level__in=[4,3,2,1])
    for query in queryset:
        # infoset = query.alidiscountcouponinfo_set.all().exclude(status=13)
        # take_number = len(infoset)
        # use_number = len(infoset.filter(status=7))
        # unclaimed_number = len(infoset.filter(status=0))
        # query.take_number = take_number
        # query.p_take_number = take_number
        # query.p_max_number = query.max_number
        # query.remain_number = query.max_number - take_number
        # query.p_remain_number = query.max_number - take_number
        # query.receive_number = take_number - unclaimed_number
        # query.p_receive_number = take_number - unclaimed_number
        # query.use_number = use_number
        # query.p_use_number = use_number
        # query.save()
        level = query.level
        if level.level == 4:
            district = level.parent_id
            prov = level.parent.parent.parent_id
            city = level.parent.parent_id
            aaaa = level.parent.parent.parent.parent_id
        elif level.level == 3:
            prov = level.parent.parent_id
            city = level.parent_id
            aaaa = level.parent.parent.parent_id
        elif level.level == 2:
            prov = level.parent_id
            aaaa = level.parent.parent_id
        else:
            aaaa = level.parent_id
        activity_id = query.activity_id
        instance = AliDiscountCouponLevel.objects.filter(level_id=aaaa, activity_id=activity_id).first()
        if not instance:
            instance = AliDiscountCouponLevel.objects.create(level_id=aaaa, activity_id=activity_id, max_number=0)
        p_max_number = instance.p_max_number + query.max_number
        p_take_number = instance.p_take_number + query.take_number
        p_remain_number = instance.p_remain_number + query.remain_number
        p_use_number = instance.p_use_number + query.use_number
        p_receive_number = instance.p_receive_number + query.receive_number
        instance.p_max_number = p_max_number
        instance.p_take_number = p_take_number
        instance.p_remain_number = p_remain_number
        instance.p_use_number = p_use_number
        instance.p_receive_number = p_receive_number
        instance.save()
        AliDiscountCouponLevelRelation.objects.create(parent=instance, child=query)
    print(len(queryset))


def wash_cashactivity():
    queryset = CashActivityLevel.objects.filter(cash_activity_id=6, level__level__in=[4,3,2,1])
    for query in queryset:
        # infoset = query.alidiscountcouponinfo_set.all().exclude(status=13)
        # take_number = len(infoset)
        # use_number = len(infoset.filter(status=7))
        # unclaimed_number = len(infoset.filter(status=0))
        # query.take_number = take_number
        # query.p_take_number = take_number
        # query.p_max_number = query.max_number
        # query.remain_number = query.max_number - take_number
        # query.p_remain_number = query.max_number - take_number
        # query.receive_number = take_number - unclaimed_number
        # query.p_receive_number = take_number - unclaimed_number
        # query.use_number = use_number
        # query.p_use_number = use_number
        # query.save()
        level = query.level
        if level.level == 4:
            district = level.parent_id
            prov = level.parent.parent.parent_id
            city = level.parent.parent_id
            aaaa = level.parent.parent.parent.parent_id
        elif level.level == 3:
            prov = level.parent.parent_id
            city = level.parent_id
            aaaa = level.parent.parent.parent_id
        elif level.level == 2:
            prov = level.parent_id
            aaaa = level.parent.parent_id
        else:
            aaaa = level.parent_id
        cash_activity_id = query.cash_activity_id
        instance = CashActivityLevel.objects.filter(level_id=city, cash_activity_id=cash_activity_id).first()
        if not instance:
            instance = CashActivityLevel.objects.create(level_id=city, cash_activity_id=cash_activity_id, max_amount=0)
        p_max_amount = instance.p_max_amount + query.max_amount
        p_take_amount = instance.p_take_amount + query.take_amount
        p_remain_amount = instance.p_remain_amount + query.remain_amount
        p_receive_amount = instance.p_receive_amount + query.receive_amount
        instance.p_max_amount = p_max_amount
        instance.p_take_amount = p_take_amount
        instance.p_remain_amount = p_remain_amount
        instance.p_receive_amount = p_receive_amount
        instance.save()
        CashActivityLevelRelation.objects.create(parent=instance, child=query)
    print(len(queryset))


def wash_merchant_data():
    queryset = Merchant.objects.all().filter(id__gt=502)
    for query in queryset:
        business_no = query.wyfMerchantID
        md5 = hashlib.md5()  # 使用MD5加密模式
        md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
        sign = md5.hexdigest()  # 完成加密并转为大写
        url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
        body = {
            'account': 'gdyouzheng',
            'shopId': sign
        }
        reaponse = requests.post(url=url, data=body)
        try:
            reaponse = reaponse.json()
        except:
            print('系统繁忙')
            continue
        merchant_data = {}
        channel_mch_id = reaponse['channel_mch_id']
        channel = Channel.objects.filter(mchid=channel_mch_id).first()
        if channel:
            merchant_data['channel_id'] = channel.id
        merchant_data['name'] = reaponse['shopName']
        merchant_data['short_name'] = reaponse['shopNickname']
        merchant_data['wyfMerchantID'] = business_no
        merchant_data['ruiyinxinMerchantID'] = sign
        merchant_data['create_time'] = datetime.datetime.now()
        if reaponse['businessType'] == '1':
            merchant_data['subject_type'] = 3
        elif reaponse['businessType'] == '2':
            merchant_data['subject_type'] = 2
        elif reaponse['businessType'] == '3':
            merchant_data['subject_type'] = 1
        else:
            merchant_data['subject_type'] = 4
        level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
        if level:
            merchant_data['level_id'] = level.id
        merchantuser = MerchantUser.objects.filter(mobile=reaponse['phone']).first()
        if merchantuser:
            merchant_data['merchantuser_id'] = merchantuser.id
        merchant_data['account_name'] = reaponse['cardName']
        merchant_data['account_bank'] = reaponse['bankName']
        merchant_data['account_number'] = reaponse['card']
        card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
        card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
        if card_copy_url:
            merchant_data['card_copy'] = card_copy
        merchant_data['identification_number'] = reaponse['identity']
        merchant_data['store_address'] = reaponse['address']
        store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
        store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
        if store_header_copy_url:
            merchant_data['store_header_copy'] = store_header_copy
        merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
        if not merchant.managerName:
            merchant.managerName = reaponse['keeper']
        if not merchant.managermobile:
            merchant.managermobile = reaponse['phone']
        if not merchant.prov_name:
            merchant.prov_name = reaponse['province']
            merchant.city_name = reaponse['city']
            merchant.district_name = reaponse['area']
        if not merchant.business_category:
            merchant.business_category_id = 1
        merchant.save()
        # if cereate and merchant.channel:
        # store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
        # store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
        # if store_header_copy_url:
        #     MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
        # store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
        # store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
        # if store_indoor_copy_url:
        #     MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
        # merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
        # merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
        # if merchantCheck_url:
        #     MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
        merchantchannel_data = {
            'merchant_id': merchant.id
        }
        if merchant.channel_id != 2:
            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
            merchantchannel_data['channel_id'] = 2
            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
            MerchantChannel.objects.update_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchant.channel_id)
            channel_response = requests.post(
                url='https://manage.gdwxyf.com/internal/searchmerchant.do',
                data={'shopId': business_no, 'account': 'gdyouzheng'},
            ).json()['showList'][0]
            merchantchannel_data['smid'] = channel_response['allchannelJson']['channel_sxf_tq']['shop_merchant_other_4']
            merchantchannel_data['channel_mchid'] = channel_response['allchannelJson']['channel_sxf_tq']['shop_merchant_no']
            merchantchannel_data['channel_id'] = 3
            merchantchannel_data['sub_mchid'] = channel_response['allchannelJson']['channel_sxf_tq']['shop_merchant_other_3']
            MerchantChannel.objects.update_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchant.channel_id)
        else:
            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
            merchantchannel_data['channel_id'] = merchant.channel_id
            merchantchannel_data['sub_mchid'] = reaponse['wx_channel_merchant_id']
            MerchantChannel.objects.update_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchant.channel_id)


def wash_error():
    queryset = CashActivityLevel.objects.filter(cash_activity=6).exclude(max_amount=0)
    # queryset = CashActivityLevel.objects.filter(id=368).exclude(max_amount=0)
    for query in queryset:
        take_amount = Decimal('0')
        remain_amount = Decimal('0')
        receive_amount = Decimal('0')
        p_take_amount = Decimal('0')
        p_remain_amount = Decimal('0')
        p_receive_amount = Decimal('0')
        data_queryset = CashActivityData.objects.filter(cash_activity_level_id=query.id)
        for data in data_queryset:
            if data.state in [1, 2]:
                take_amount += data.amount
                p_take_amount += data.amount
                if data.state == 2:
                    receive_amount += data.amount
                    p_receive_amount += data.amount
        query.take_amount = take_amount
        query.p_take_amount = p_take_amount
        query.receive_amount = receive_amount
        query.p_receive_amount = p_receive_amount
        query.remain_amount = query.max_amount - take_amount
        query.p_remain_amount = query.max_amount - take_amount
        query.save()
        print(query.id)


def wash_error1():
    # query = CashActivityLevel.objects.get(id=3666)
    # query.take_amount += Decimal('600')
    # query.p_take_amount += Decimal('600')
    # query.remain_amount -= Decimal('600')
    # query.p_remain_amount -= Decimal('600')
    # query.max_amount += Decimal('100')
    # query.p_max_amount += Decimal('100')
    # query.save()
    # relation_set = query.child_set.all()
    # for relation in relation_set:
    #     parent = relation.parent
    #     parent.p_take_amount += Decimal('600')
    #     parent.p_remain_amount -= Decimal('600')
    #     parent.save()

    activity_level = CashActivityLevel.objects.get(id=3826)
    activity = activity_level.cash_activity
    activity.distributed_amount += 200
    activity.save()
    activity_level.receive_amount += 200
    activity_level.p_receive_amount += 200
    activity_level.save()
    relation_set = activity_level.child_set.all()
    for relation in relation_set:
        parent = relation.parent
        parent.p_receive_amount += 200
        parent.save()


def update_max_amount():
    # query_set = CashActivityLevel.objects.filter(id__in=[377,378,379,329,333,334,335,340,324,318])
    # query_set = CashActivityLevel.objects.filter(id__in=[344,352,354,])
    query_set = CashActivityLevel.objects.filter(id__in=[1742])
    amount = 200
    for query in query_set:
        # query.max_amount += amount
        # query.p_max_amount += amount
        # query.remain_amount -= amount
        query.p_remain_amount -= amount
        # query.take_amount += amount
        query.p_take_amount += amount
        query.save()


def wash_payeeFullName():
    queryset = CashActivityData.objects.filter(mchid='alipay', payeeFullName='1*', state=2)
    url = 'https://mbillexprod.alipay.com/enterprise/fundAccountDetail.json'
    body = {
        'billUserId': '2088631976752358',
        'querySettleAccount': 'false',
        'pageSize': '50',
        'pageNum': '1',
        'startDateInput': '2023-02-09 00:00:00',
        'endDateInput': '2023-02-09 23:59:59',
        'queryEntrance': '1',
        'showType': '0',
        'accountType': ''
    }
    platform = Channel.objects.filter(id=1, channel_type=2).first()
    headers = {
        'Cookie': 'JSESSIONID=RZ42G83HWN6LUSEsBvCdPX4z3dg8orauthRZ54GZ00; cna=ap9mGQZnnScCAT2MoMAlIFQE; credibleMobileSendTime=-1; ctuMobileSendTime=-1; riskMobileBankSendTime=-1; riskCredibleMobileSendTime=-1; riskMobileCreditSendTime=-1; riskOriginalAccountMobileSendTime=-1; mobileSendTime=-1; riskMobileAccoutSendTime=-1; CLUB_ALIPAY_COM=2088631976752358; iw.userid="K1iSL19hOZISIRfr5Nh/1w=="; ali_apache_tracktmp="uid=2088631976752358"; session.cookieNameId=ALIPAYJSESSIONID; ALI_PAMIR_SID=U35PKVQ+nkPaSVxLV9vajlSYTM1#mbFKpEsyQ865jayXidM8QjM1; __TRACERT_COOKIE_bucUserId=2088631976752358; csrfToken=3PLbKBYrRLZoENrYzYQlh56E; JSESSIONID=E3BE7CEDF8AC4B63B18CD2223B710D95; spanner=pxbt33P12FgsS7a9hqb5tsK89XOFVuHwXt2T4qEYgj0=; LoginForm=alipay_login_auth; isg=BGFhXfGlptTMoAth9lZ5I9UscC17DtUAyNFNm8M212jHKoP8C19a0Kp7jl6s5204; l=fBagAivmLxstUO-OBOfaFurza77OSIRYYuPzaNbMi9fPO2CB5zCcW6-8ZvY6C3GVFsCWR3PZC7jvBeYBqQAonxvTCziq1fMmndLHR35..; tfstk=cYqcB0bZLruXHSsTNSifxvbMy9SdwYxZtlr74TGrHgAXtB5mHU8U_rBoi6125; auth_goto_http_type=https; alipay="K1iSL19hOZISIRfr5Nh/12FkTos5Dc7C8tuyj0IeSSu3Sh9PmbMM1A=="; ctoken=iSOtYe2E-zUVRDAE; auth_jwt=e30.eyJleHAiOjE2NzU5MzM5MzE1NTksInJsIjoiNSwwLDI3LDE5LDI4LDQ2LDMwLDEzLDEwIiwic2N0IjoieU5mODhmNDE4QzVaYys0MW0rSWFSMTE5ZmJJWXpGZzJEalh1SVJhIiwidWlkIjoiMjA4ODYzMTk3Njc1MjM1OCJ9.j60gJwIGwYfCJNwIWbHdzcoZ1nWCRid8BKCasEtVjog; ALIPAYJSESSIONID=RZ42AAGYCxN9YB3riq9Dvj0y2JiMy2authRZ54GZ00; rtk=dOw81uAbvcHzQEFOUODNCCrlBq0dw/fGMI9o3MeuS67aw/lESI5; zone=GZ00C',
        'referer': 'https://b.alipay.com/',
        # "X-Requested-With": "XMLHttpRequest",
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    for query in queryset:
        body['tradeNo'] = query.payment_no
        response = requests.post(url=url, headers=headers, data=body)
        result = response.json()
        if result['status'] == 'succeed':
            query.payeeFullName = f"({result['result']['detail'][0]['otherAccountEmail']})"
            query.save()
        print(response.json())


def wash_record_activity_id():
    queryset = CashActivityLevelRecord.objects.filter(activity_id__isnull=True)
    for query in queryset:
        query.activity_id = query.activity_level.cash_activity_id
        query.save()
        print(query.id)



def wash_activity_data():
    activity = CashActivity.objects.get(id=112)
    cashactivitydata_set = activity.cashactivitydata_set.all().filter(state__in=[1,2])


from activities.models import LuckyBagChildActivityRule

def create_lucky_rule():
    today = datetime.datetime.now() + datetime.timedelta(days=40)
    for i in range(30):
        today1 = (today + datetime.timedelta(days=i)).strftime('%Y-%m-%d 00:00:00')
        print(today1)
        for i in range(500):
            # for j in range(89):
            data = {}
            data['lucky_bag'] = 10
            data['validity_time'] = today1
            LuckyBagChildActivityRule.objects.create(**data)
        for i in range(500):
            # for j in range(89):
            data = {}
            data['lucky_bag'] = 1
            data['validity_time'] = today1
            LuckyBagChildActivityRule.objects.create(**data)
        for i in range(2, 10):
            for j in range(125):
                data = {}
                data['lucky_bag'] = i
                data['validity_time'] = today1
                LuckyBagChildActivityRule.objects.create(**data)




if __name__ == '__main__':
    pass
    create_lucky_rule()